package cn.tedu.baking.controller;

import cn.tedu.baking.response.JsonResult;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@RestController
@RequestMapping("/v1")
public class UploadController {
    @Value("${file-path}")
    private String dirPath;

    @PostMapping("upload")
    public JsonResult upload(MultipartFile file) throws IOException {
        //1.获取原始文件名
        String fileName = file.getOriginalFilename();
        //2.获取文件名中的后缀名
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        //3.UUID.randomUUID()得到唯一的字符串作为文件名
        fileName = UUID.randomUUID()+suffix;
        //4.指定一个文件夹路径用来存图片
        //String dirPath = "d:/files";
        //5.准备日期路径
        SimpleDateFormat sdf = new SimpleDateFormat("/yyyy/MM/dd/");
        String datePath = sdf.format(new Date());
        //6.准备对象，封装上面的文件夹路径与日期路径
        File dirFile = new File(dirPath+datePath);
        //7.如果文件夹不存在，创建文件夹
        if(!dirFile.exists()){
            dirFile.mkdirs();
        }
        //8.准备一个完整的文件路径
        String filePath = dirPath+datePath+fileName;
        System.out.println("file = " + filePath);
        //9.把文件保存在指定的路径
        file.transferTo(new File(filePath));
        //10.将路径返回给前端
        return JsonResult.ok(datePath+fileName);
    }

    @PostMapping("remove")
    public JsonResult remove(String imgUrl){
        new File(dirPath+imgUrl).delete();
        return JsonResult.ok();
    }
}
